// API 接口配置和类型定义

// 后端API基础URL配置
const BACKEND_BASE_URL = 'http://localhost:8232'
const API_PREFIX = '/api/admin'

export interface User {
  id: number
  username: string
  email: string
  name?: string
  company?: string
  status: number // 1: 正常, 0: 禁用
  createdAt: Date
  lastLoginTime?: Date
}

export interface Admin {
  id: number
  username: string
  email?: string
  nickname?: string
  status: number
  loginCount: number
  lastLoginTime?: Date
  createdAt: Date
}

export interface NewsArticle {
  id: string
  title: string
  content: string
  summary: string
  category: string
  status: 'draft' | 'published' | 'archived'
  tags: string  // 修改为字符串，逗号分隔
  authorId: number
  authorName: string
  publishedAt?: Date
  createdAt: Date
  updatedAt: Date
  views: number
  likes: number
  comments: number
}

export interface BusinessPlan {
  id: string
  title: string
  industry: string
  stage: string
  description: string
  authorId: number
  authorName: string
  status: 'draft' | 'completed' | 'reviewed'
  createdAt: Date
  updatedAt: Date
}

export interface DashboardStats {
  totalUsers: number
  activeUsers: number
  totalNews: number
  totalPlans: number
  todayRegistrations: number
  todayLogins: number
}

export interface LoginResponse {
  success: boolean
  message?: string
  token?: string
  user?: {
    id: number
    username: string
    email: string
    nickname?: string
    role: string
  }
}

// 真实API调用
class AdminAPI {
  private baseUrl = BACKEND_BASE_URL + API_PREFIX

  // 处理API请求的通用方法
  private async makeRequest(url: string, options: RequestInit = {}): Promise<any> {
    const defaultOptions: RequestInit = {
      credentials: 'include', // 使用session而不是token
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      mode: 'cors', // 明确指定CORS模式
    }

    const finalOptions = {
      ...defaultOptions,
      ...options,
      headers: {
        ...defaultOptions.headers,
        ...options.headers,
      },
    }

    try {
      console.log('Making API request to:', url, 'with options:', finalOptions)
      const response = await fetch(url, finalOptions)
      
      console.log('Response status:', response.status)
      
      if (!response.ok) {
        const errorText = await response.text()
        console.error('Response error:', errorText)
        throw new Error(`HTTP ${response.status}: ${errorText}`)
      }

      const data = await response.json()
      console.log('Response data:', data)
      
      // 检查后端返回的标准格式
      if (data && data.code === 200) {
        return data.data
      } else if (data && Array.isArray(data)) {
        // 如果直接返回数组，则直接使用
        return data
      } else if (data && typeof data === 'object') {
        // 如果直接返回对象，则直接使用
        return data
      } else {
        throw new Error(data?.message || '请求失败')
      }
    } catch (error) {
      console.error('API请求错误:', error)
      // 在开发环境下使用模拟数据作为fallback
      if (process.env.NODE_ENV === 'development') {
        console.log('Using fallback mock data for:', url)
        return this.getFallbackData(url)
      }
      throw error
    }
  }

  // 获取fallback数据
  private getFallbackData(url: string): any {
    if (url.includes('/stats/overview')) {
      return {
        totalUsers: 150,
        activeUsers: 120,
        totalNews: 45,
        totalPlans: 28,
        todayRegistrations: 12,
        todayLogins: 89
      }
    } else if (url.includes('/frontend-users/recent')) {
      return Promise.resolve().then(() => this.getMockRecentUsers())
    } else if (url.includes('/frontend-users')) {
      return Promise.resolve().then(() => this.getMockAllUsers())
    } else if (url.includes('/admin-users/list')) {
      return Promise.resolve().then(() => this.getMockAllAdmins())
    } else if (url.includes('/news')) {
      return Promise.resolve().then(() => this.getMockAllNews())
    } else if (url.includes('/business-plans')) {
      return Promise.resolve().then(() => this.getMockAllBusinessPlans())
    }
    return []
  }

  // 获取仪表板统计数据
  async getDashboardStats(): Promise<DashboardStats> {
    return await this.makeRequest(`${this.baseUrl}/stats/overview`)
  }

  // 获取最近注册用户
  async getRecentUsers(limit = 5): Promise<User[]> {
    const data = await this.makeRequest(`${this.baseUrl}/frontend-users/recent?limit=${limit}`)
    return data.map((user: any) => ({
      ...user,
      createdAt: new Date(user.createdAt),
      lastLoginTime: user.lastLoginTime ? new Date(user.lastLoginTime) : undefined
    }))
  }
  // 获取所有用户
  async getAllUsers(): Promise<User[]> {
    const data = await this.makeRequest(`${this.baseUrl}/frontend-users`)
    return data.map((user: any) => ({
      ...user,
      createdAt: new Date(user.createdAt),
      lastLoginTime: user.lastLoginTime ? new Date(user.lastLoginTime) : undefined
    }))
  }

  // 获取所有管理员
  async getAllAdmins(): Promise<Admin[]> {
    const data = await this.makeRequest(`${this.baseUrl}/admin-users/list`)
    return data.map((admin: any) => ({
      ...admin,
      createdAt: new Date(admin.createdAt),
      lastLoginTime: admin.lastLoginTime ? new Date(admin.lastLoginTime) : undefined
    }))
  }

  // 获取新闻文章
  async getAllNews(): Promise<NewsArticle[]> {
    const data = await this.makeRequest(`${this.baseUrl}/news`)
    return data.map((article: any) => ({
      ...article,
      createdAt: new Date(article.createdAt),
      updatedAt: new Date(article.updatedAt),
      publishedAt: article.publishedAt ? new Date(article.publishedAt) : undefined
    }))
  }

  // 获取商业计划书
  async getAllBusinessPlans(): Promise<BusinessPlan[]> {
    try {
      const data = await this.makeRequest(`${this.baseUrl}/business-plans`)
      return data.map((plan: any) => ({
        ...plan,
        createdAt: new Date(plan.createdAt),
        updatedAt: new Date(plan.updatedAt)
      }))
    } catch (error) {
      console.error('Get all business plans API error:', error)
      // 开发环境fallback
      if (process.env.NODE_ENV === 'development') {
        return this.getMockAllBusinessPlans()
      }
      throw error
    }
  }

  // 模拟数据方法
  private getMockRecentUsers(limit = 5): Promise<User[]> {
    return Promise.resolve([
      {
        id: 1,
        username: 'zhangsan',
        email: 'zhangsan@example.com',
        name: '张三',
        company: '创新科技有限公司',
        status: 1,
        createdAt: new Date('2025-01-15'),
        lastLoginTime: new Date('2025-01-15 10:30:00')
      },
      {
        id: 2,
        username: 'lisi',
        email: 'lisi@example.com',
        name: '李四',
        company: '未来创业公司',
        status: 1,
        createdAt: new Date('2025-01-14'),
        lastLoginTime: new Date('2025-01-14 15:20:00')
      },
      {
        id: 3,
        username: 'wangwu',
        email: 'wangwu@example.com',
        name: '王五',
        status: 0,
        createdAt: new Date('2025-01-13'),
      }
    ].slice(0, limit))
  }

  private getMockAllUsers(): Promise<User[]> {
    const users: User[] = []
    for (let i = 1; i <= 50; i++) {
      users.push({
        id: i,
        username: `user${i}`,
        email: `user${i}@example.com`,
        name: `用户${i}`,
        company: i % 3 === 0 ? `公司${i}` : undefined,
        status: Math.random() > 0.2 ? 1 : 0,
        createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
        lastLoginTime: Math.random() > 0.3 ? new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000) : undefined
      })
    }
    return Promise.resolve(users)
  }

  private getMockAllAdmins(): Promise<Admin[]> {
    return Promise.resolve([
      {
        id: 1,
        username: 'admin',
        email: 'admin@entrepreneur-home.com',
        nickname: '超级管理员',
        status: 1,
        loginCount: 156,
        lastLoginTime: new Date(),
        createdAt: new Date('2024-01-01')
      },
      {
        id: 2,
        username: 'manager',
        email: 'manager@entrepreneur-home.com',
        nickname: '内容管理员',
        status: 1,
        loginCount: 89,
        lastLoginTime: new Date(Date.now() - 2 * 60 * 60 * 1000),
        createdAt: new Date('2024-02-15')
      },
      {
        id: 3,
        username: 'editor',
        email: 'editor@entrepreneur-home.com',
        nickname: '编辑员',
        status: 0,
        loginCount: 45,
        lastLoginTime: new Date(Date.now() - 24 * 60 * 60 * 1000),
        createdAt: new Date('2024-03-10')
      }
    ])
  }

  private getMockAllNews(): Promise<NewsArticle[]> {
    const news: NewsArticle[] = []
    for (let i = 1; i <= 20; i++) {
      news.push({
        id: `news_${i}`,
        title: `创业资讯标题 ${i}`,
        content: `这是第${i}篇创业资讯的详细内容...`,
        summary: `这是第${i}篇创业资讯的摘要`,
        category: ['startup', 'funding', 'policy', 'tech'][i % 4],
        status: ['draft', 'published', 'archived'][Math.floor(Math.random() * 3)] as any,
        tags: `标签${i},创业`,
        authorId: 1,
        authorName: '管理员',
        publishedAt: Math.random() > 0.5 ? new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000) : undefined,
        createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000),
        views: Math.floor(Math.random() * 10000),
        likes: Math.floor(Math.random() * 1000),
        comments: Math.floor(Math.random() * 100)
      })
    }
    return Promise.resolve(news)
  }

  private getMockAllBusinessPlans(): Promise<BusinessPlan[]> {
    const plans: BusinessPlan[] = []
    for (let i = 1; i <= 15; i++) {
      plans.push({
        id: `plan_${i}`,
        title: `商业计划书 ${i}`,
        industry: ['科技', '餐饮', '教育', '医疗', '金融'][i % 5],
        stage: ['创意阶段', '初创阶段', '成长阶段'][i % 3],
        description: `这是第${i}个商业计划书的描述`,
        authorId: i,
        authorName: `用户${i}`,
        status: ['draft', 'completed', 'reviewed'][Math.floor(Math.random() * 3)] as any,
        createdAt: new Date(Date.now() - Math.random() * 60 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000)
      })
    }
    return Promise.resolve(plans)
  }

  // 创建用户
  async createUser(userData: any): Promise<User> {
    const data = await this.makeRequest(`${this.baseUrl}/frontend-users`, {
      method: 'POST',
      body: JSON.stringify(userData)
    })
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      lastLoginTime: data.lastLoginTime ? new Date(data.lastLoginTime) : undefined
    }
  }

  // 创建管理员
  async createAdmin(adminData: any): Promise<Admin> {
    const data = await this.makeRequest(`${this.baseUrl}/admin-users/create`, {
      method: 'POST',
      body: JSON.stringify(adminData)
    })
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      lastLoginTime: data.lastLoginTime ? new Date(data.lastLoginTime) : undefined
    }
  }

  // 创建新闻文章
  async createNews(newsData: any): Promise<NewsArticle> {
    const data = await this.makeRequest(`${this.baseUrl}/news`, {
      method: 'POST',
      body: JSON.stringify(newsData)
    })
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt),
      publishedAt: data.publishedAt ? new Date(data.publishedAt) : undefined
    }
  }

  // 创建商业计划模板
  async createBusinessPlanTemplate(templateData: any): Promise<any> {
    const data = await this.makeRequest(`${this.baseUrl}/business-plans/templates`, {
      method: 'POST',
      body: JSON.stringify(templateData)
    })
    return data
  }

  // 更新用户状态
  async updateUserStatus(userId: number, status: number): Promise<any> {
    return await this.makeRequest(`${this.baseUrl}/frontend-users/${userId}/status`, {
      method: 'PUT',
      body: JSON.stringify({ status })
    })
  }

  // 删除用户
  async deleteUser(userId: number): Promise<any> {
    return await this.makeRequest(`${this.baseUrl}/frontend-users/${userId}`, {
      method: 'DELETE'
    })
  }

  // 更新新闻文章
  async updateNews(newsId: string, newsData: any): Promise<NewsArticle> {
    const data = await this.makeRequest(`${this.baseUrl}/news/${newsId}`, {
      method: 'PUT',
      body: JSON.stringify(newsData)
    })
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt),
      publishedAt: data.publishedAt ? new Date(data.publishedAt) : undefined
    }
  }

  // 删除新闻文章
  async deleteNews(newsId: string): Promise<any> {
    return await this.makeRequest(`${this.baseUrl}/news/${newsId}`, {
      method: 'DELETE'
    })
  }

  // 获取新闻文章详情
  async getNewsById(newsId: string): Promise<NewsArticle> {
    const data = await this.makeRequest(`${this.baseUrl}/news/${newsId}`)
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt),
      publishedAt: data.publishedAt ? new Date(data.publishedAt) : undefined
    }
  }

  // 发布新闻
  async publishNews(newsId: string): Promise<any> {
    return await this.makeRequest(`${this.baseUrl}/news/${newsId}/publish`, {
      method: 'PUT'
    })
  }

  // 取消发布新闻
  async unpublishNews(newsId: string): Promise<any> {
    return await this.makeRequest(`${this.baseUrl}/news/${newsId}/unpublish`, {
      method: 'PUT'
    })
  }

  // 更新管理员
  async updateAdmin(adminId: number, adminData: any): Promise<Admin> {
    const data = await this.makeRequest(`${this.baseUrl}/admin-users/update/${adminId}`, {
      method: 'PUT',
      body: JSON.stringify(adminData)
    })
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      lastLoginTime: data.lastLoginTime ? new Date(data.lastLoginTime) : undefined
    }
  }

  // 删除管理员
  async deleteAdmin(adminId: number): Promise<any> {
    return await this.makeRequest(`${this.baseUrl}/admin-users/delete/${adminId}`, {
      method: 'DELETE'
    })
  }

  // 获取管理员详情
  async getAdminById(adminId: number): Promise<Admin> {
    const data = await this.makeRequest(`${this.baseUrl}/admin-users/${adminId}`)
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      lastLoginTime: data.lastLoginTime ? new Date(data.lastLoginTime) : undefined
    }
  }

  // 更新管理员状态
  async updateAdminStatus(adminId: number, status: number): Promise<any> {
    return await this.makeRequest(`${this.baseUrl}/admin-users/status/${adminId}`, {
      method: 'PUT',
      body: JSON.stringify({ status })
    })
  }

  // 获取用户详情
  async getUserById(userId: number): Promise<User> {
    const data = await this.makeRequest(`${this.baseUrl}/frontend-users/${userId}`)
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      lastLoginTime: data.lastLoginTime ? new Date(data.lastLoginTime) : undefined
    }
  }

  // 更新用户
  async updateUser(userId: number, userData: any): Promise<User> {
    const data = await this.makeRequest(`${this.baseUrl}/frontend-users/${userId}`, {
      method: 'PUT',
      body: JSON.stringify(userData)
    })
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      lastLoginTime: data.lastLoginTime ? new Date(data.lastLoginTime) : undefined
    }
  }

  // 获取商业计划详情
  async getBusinessPlanById(planId: string): Promise<BusinessPlan> {
    const data = await this.makeRequest(`${this.baseUrl}/business-plans/${planId}`)
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt)
    }
  }

  // 更新商业计划
  async updateBusinessPlan(planId: string, planData: any): Promise<BusinessPlan> {
    const data = await this.makeRequest(`${this.baseUrl}/business-plans/${planId}`, {
      method: 'PUT',
      body: JSON.stringify(planData)
    })
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt)
    }
  }

  // 删除商业计划
  async deleteBusinessPlan(planId: string): Promise<any> {
    return await this.makeRequest(`${this.baseUrl}/business-plans/${planId}`, {
      method: 'DELETE'
    })
  }
}

export const adminAPI = new AdminAPI()

// 身份验证 API
class AuthAPI {
  private baseUrl = BACKEND_BASE_URL + API_PREFIX + '/auth'

  // 管理员登录
  async login(username: string, password: string): Promise<LoginResponse> {
    // 输入验证
    if (!username || !password) {
      return {
        success: false,
        message: '用户名和密码不能为空'
      }
    }

    try {
      const response = await fetch(`${this.baseUrl}/login`, {
        method: 'POST',
        credentials: 'include', // 包含cookies
        mode: 'cors',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify({
          username: username.trim(),
          password: password.trim()
        })
      })

      console.log('Login response status:', response.status)

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
      }

      const data = await response.json()
      console.log('Login response data:', data)

      if (data.code === 200) {
        return {
          success: true,
          message: data.message,
          user: data.data.admin
        }
      } else {
        return {
          success: false,
          message: data.message || '登录失败'
        }
      }
    } catch (error) {
      console.error('[AuthAPI] 登录错误:', error)
      
      // 开发环境下使用模拟登录
      if (process.env.NODE_ENV === 'development') {
        console.log('[AuthAPI] Using mock login in development')
        return this.mockLogin(username, password)
      }
      
      return {
        success: false,
        message: '网络错误或服务器异常'
      }
    }
  }

  // 模拟登录（开发环境）
  private mockLogin(username: string, password: string): Promise<LoginResponse> {
    return new Promise((resolve) => {
      try {
        setTimeout(() => {
          console.log('[AuthAPI] 模拟登录验证:', { username, password })
          
          // 模拟验证逻辑
          if (username === 'admin' && password === 'admin123') {
            const mockResponse = {
              success: true,
              token: 'mock-jwt-token-' + Date.now(),
              user: {
                id: 1,
                username: 'admin',
                email: 'admin@entrepreneur-home.com',
                nickname: '超级管理员',
                role: 'admin'
              }
            }
            console.log('[AuthAPI] 模拟登录成功:', mockResponse)
            
            // 保存到localStorage以便后续使用
            if (typeof window !== 'undefined') {
              localStorage.setItem('admin_token', mockResponse.token)
              localStorage.setItem('admin_user', JSON.stringify(mockResponse.user))
            }
            
            resolve(mockResponse)
          } else {
            const errorResponse = {
              success: false,
              message: '用户名或密码错误'
            }
            console.log('[AuthAPI] 模拟登录失败:', errorResponse)
            resolve(errorResponse)
          }
        }, 500) // 缩短延迟时间
      } catch (error) {
        console.error('[AuthAPI] 模拟登录异常:', error)
        resolve({
          success: false,
          message: '模拟登录异常'
        })
      }
    })
  }

  // 验证session
  async validateToken(): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseUrl}/validate`, {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      const data = await response.json()
      return data.code === 200
    } catch (error) {
      console.log('[AuthAPI] Session验证失败:', error)
      
      // 开发环境下检查localStorage中的token
      if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
        const token = localStorage.getItem('admin_token')
        const user = localStorage.getItem('admin_user')
        
        if (token && user) {
          console.log('[AuthAPI] 开发环境：使用localStorage中的token')
          return true
        }
      }
      
      return false
    }
  }

  // 注销
  async logout(): Promise<void> {
    try {
      await fetch(`${this.baseUrl}/logout`, {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (error) {
      console.log('[AuthAPI] 注销请求失败:', error)
    }
  }

  // 获取当前用户信息
  async getCurrentUser(): Promise<LoginResponse['user']> {
    try {
      const response = await fetch(`${this.baseUrl}/me`, {
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      const data = await response.json()
      
      if (data.code === 200) {
        return data.data
      } else {
        throw new Error(data.message || '获取用户信息失败')
      }
    } catch (error) {
      console.log('[AuthAPI] 获取用户信息失败:', error)
      
      // 开发环境下尝试从localStorage获取用户信息
      if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
        const savedUser = localStorage.getItem('admin_user')
        if (savedUser) {
          try {
            const user = JSON.parse(savedUser)
            console.log('[AuthAPI] 开发环境：从localStorage获取用户信息')
            return user
          } catch (e) {
            console.warn('解析localStorage用户信息失败:', e)
          }
        }
      }
      
      throw error
    }
  }

  // 更新当前用户个人信息
  async updateProfile(profileData: { nickname?: string; email?: string; phone?: string }): Promise<any> {
    try {
      const response = await fetch(`${this.baseUrl}/profile`, {
        method: 'PUT',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(profileData)
      })

      const data = await response.json()
      
      if (data.code === 200) {
        return data.data
      } else {
        throw new Error(data.message || '更新个人信息失败')
      }
    } catch (error) {
      console.error('[AuthAPI] 更新个人信息失败:', error)
      throw error
    }
  }

  // 修改密码
  async changePassword(passwordData: { oldPassword: string; newPassword: string }): Promise<any> {
    try {
      const response = await fetch(`${this.baseUrl}/password`, {
        method: 'PUT',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(passwordData)
      })

      const data = await response.json()
      
      if (data.code === 200) {
        return data.data
      } else {
        throw new Error(data.message || '修改密码失败')
      }
    } catch (error) {
      console.error('[AuthAPI] 修改密码失败:', error)
      throw error
    }
  }
}

export const authAPI = new AuthAPI()